// MathJax和CKEditor配置
// 等待MathJax加载完成
function initMathJax() {
    if (window.MathJax) {
        return MathJax.startup.promise.then(function() {
            console.log('MathJax initialized successfully');
            return true;
        }).catch(function(error) {
            console.error('MathJax initialization failed:', error);
            return false;
        });
    } else {
        console.error('MathJax library not loaded');
        return Promise.resolve(false);
    }
}

// 初始化CKEditor和MathJax的联动
function initEditorMathJax() {
    // 确保CKEditor已加载
    if (window.CKEDITOR) {
        // 监听所有CKEditor实例就绪事件
        CKEDITOR.on('instanceReady', function(evt) {
            var editor = evt.editor;
            console.log('CKEditor instance ready:', editor.name);
            
            // 监听内容变化事件
            editor.on('change', function() {
                try {
                    // 先更新预览区域
                    if (editor.name === 'question') {
                        var previewQuestion = document.getElementById('preview-question');
                        if (previewQuestion) {
                            previewQuestion.innerHTML = editor.getData();
                        }
                    } else if(editor.name === 'answer') {
                        var previewAnswer = document.getElementById('preview-answer');
                        if(previewAnswer) {
                            previewAnswer.innerHTML = editor.getData();
                        }
                    }

                    // 再触发MathJax排版
                    if (window.MathJax) {
                        MathJax.typeset();
                        console.log('MathJax typesetting triggered');
                    }
                } catch (e) {
                    console.error('Editor change handler failed:', e);
                }
            });

            // 初始排版
            setTimeout(function() {
                if (window.MathJax) {
                    MathJax.typeset();
                    console.log('Initial MathJax typesetting');
                }
            }, 500);
        });
    } else {
        console.error('CKEditor not loaded');
    }
}

// 执行初始化
initMathJax().then(function(success) {
    if (success) {
        initEditorMathJax();
    } else {
        // 尝试重新加载MathJax
        console.log('Attempting to reload MathJax...');
        var script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js';
        script.onload = function() {
            console.log('MathJax reloaded');
            initMathJax().then(function(reloadSuccess) {
                if (reloadSuccess) {
                    initEditorMathJax();
                }
            });
        };
        document.head.appendChild(script);
    }
});